package com.huawei.fastble;

import com.huawei.fastble.adapter.CharacterItemProvider;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.bluetooth.ble.GattCharacteristic;
import ohos.bluetooth.ble.GattService;

import java.util.ArrayList;
import java.util.List;

/**
 * CharacteristicListAbility
 */
public class CharacteristicListAbility extends Ability {
   private CharacterItemProvider provider;
    private GattService gattService;
    private ListContainer listContainer;

    private List<GattCharacteristic> gattCharacteristics;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_characteristiclist);
        gattCharacteristics = new ArrayList<>();
        gattService = FastBleMyApplication.getGattService();

        listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_chara);

        if (gattService != null && gattService.getCharacteristics() != null) {
            gattCharacteristics.addAll(gattService.getCharacteristics());
            provider = new CharacterItemProvider(this, gattCharacteristics);
            listContainer.setItemProvider(provider);
            listContainer.setItemClickedListener(
                    new ListContainer.ItemClickedListener() {
                        @Override
                        public void onItemClicked(
                                ListContainer listContainer, Component component, int position, long l) {
                            final GattCharacteristic characteristic = gattCharacteristics.get(position);

                            intentToNext(characteristic, position);
                        }
                    });
        }
    }

    private void intentToNext(GattCharacteristic characteristic, int position) {
        FastBleMyApplication.setGattCharacteristic(characteristic);
        Intent intent = new Intent();
        Operation operationBuilder =
                new Intent.OperationBuilder()
                        .withAbilityName("com.huawei.fastble.CharacteristicOperationAbility")
                        .withDeviceId("")
                        .withBundleName(getBundleName())
                        .build();
        intent.setParam("properties", provider.propertiesStrs.get(position));
        intent.setOperation(operationBuilder);
        startAbility(intent);
    }
}
